/************************************/
/***********************************/
import $ from 'jquery';
export default async (url = '', { data = {}, type = 'POST', method = 'ajax' } = {}) => {
  type = type.toUpperCase();
  //url = baseUrl+url;
  let dataStr = $.param(data); //数据拼接字符串
  if (type == 'GET' && dataStr !== '') {
    if (url.indexOf('?') != -1) {
      url = url + '&' + dataStr;
    } else {
      url = url + '?' + dataStr;
    }
  }
  if (window.fetch && method == 'fetch') {
    let requestConfig = {
      //credentials: 'include',
      method: type,
      /*headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},*/
      mode: 'cors',
      cache: 'force-cache'
    };
    if (type == 'POST') {
      Object.defineProperty(requestConfig, 'body', {
        value: JSON.stringify(data)
      });
    }
    try {
      const response = await fetch(url, requestConfig);
      const responseJson = await response.json().then(function (res) {
        return res;
      });
      return responseJson;
    } catch (error) {
      throw new Error(error);
    }
  } else {
    return new Promise((resolve, reject) => {
      let requestObj;
      if (window.XMLHttpRequest) {
        requestObj = new XMLHttpRequest();
      } else {
        requestObj = new ActiveXObject();
      }
      requestObj.open(type, url, true);
      requestObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      requestObj.send(dataStr);
      requestObj.onreadystatechange = () => {
        if (requestObj.readyState == 4) {
          if (requestObj.status == 200) {
            let obj = requestObj.response;
            if (typeof obj !== 'object') {
              obj = JSON.parse(obj);
            }
            resolve(obj);
          } else {
            reject(requestObj);
          }
        }
      };
    });
  }
};
